package de.duester.genealogy;

import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import de.duester.genealogy.adapter.EventListAdapter;
import de.duester.genealogy.adapter.EventTypeListAdapter;
import de.duester.genealogy.model.Event;
import de.duester.genealogy.model.EventCode;
import de.duester.genealogy.model.Person;
import de.duester.genealogy.model.PersonEvent;
import de.duester.genealogy.model.service.EventService;
import de.duester.genealogy.model.service.PersonService;

public class PersonEditActivity extends Activity implements OnClickListener, OnTabChangeListener {
	private TabHost tabHost;
	private EditText etName, etSurname;
	private Spinner spGender;
	private Button btnSave, btnFamilyOverview;

	private ListView lvPersonEvents;

	private Person person;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_bar);
		init();
	}

	private void init() {
		LayoutInflater li = getLayoutInflater();
		View personEditPersonData = li.inflate(R.layout.activity_person_edit_person_data, null);

		etName = (EditText) personEditPersonData.findViewById(R.id.etPersonEditName);
		etSurname = (EditText) personEditPersonData.findViewById(R.id.etPersonEditSurname);

		spGender = (Spinner) personEditPersonData.findViewById(R.id.spPersonEditGender);

		btnSave = (Button) personEditPersonData.findViewById(R.id.btnSave);
		btnSave.setOnClickListener(this);

		btnFamilyOverview = (Button) personEditPersonData.findViewById(R.id.btnFamilyOverview);
		btnFamilyOverview.setOnClickListener(this);

		long personId = getIntent().getLongExtra("personId", -1);

		if (personId == -1) {
			// Person erstellen
			person = new Person();
			Utility.getDaoSession().getPersonDao().insert(person);

			// Ereignis Geburt erstellen
			Event birth = new Event(null, "birth");
			Utility.getDaoSession().getEventDao().insert(birth);
			PersonEvent pe = new PersonEvent(null, person.getId(), birth.getId(), "child");
			Utility.getDaoSession().getPersonEventDao().insert(pe);
		} else {
			person = Utility.getDaoSession().getPersonDao().load(personId);

			etName.setText(person.getName());
			etSurname.setText(person.getSurname());

			spGender.setSelection(person.getGender());
		}

		lvPersonEvents = new ListView(this);
		lvPersonEvents.setAdapter(new EventListAdapter(this, android.R.layout.simple_list_item_1,
				person, PersonService.getEvents(person)));

		tabHost = (TabHost) findViewById(android.R.id.tabhost);
		tabHost.setOnTabChangedListener(this);
		tabHost.setup();

		createTab(R.string.ttlPersonData, personEditPersonData);
		createTab(R.string.ttlPersonEvents, lvPersonEvents);

		tabHost.setCurrentTab(0);
	}

	private void createTab(int textId, View contentView) {
		TabSpec spec = tabHost.newTabSpec(getString(textId));
		spec.setIndicator(getTabIndicator(textId));
		spec.setContent(getTabContent(contentView));
		tabHost.addTab(spec);
	}

	private View getTabIndicator(int textId) {
		LayoutInflater li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
		View v = li.inflate(R.layout.tab_bar_element, null);
		TextView tv = (TextView) v.findViewById(R.id.tvTabBarText);
		tv.setText(textId);
		return v;
	}

	private TabContentFactory getTabContent(final View v) {
		return new TabContentFactory() {

			@Override
			public View createTabContent(String tag) {
				return v;
			}
		};
	}

	@Override
	public void onClick(View v) {
		if (v == btnSave) {
			savePerson();
			if (checkCreatedBirthDate()) {
				Utility.getDB().setTransactionSuccessful();
				Utility.getDB().endTransaction();
				Utility.refreshSession();
				setResult(RESULT_OK);
				finish();
			} else
				Toast.makeText(this, R.string.msgBirthDateNotSet, Toast.LENGTH_SHORT).show();
		} else if (v == btnFamilyOverview) {
			savePerson();
			Intent intent = new Intent(this, FamilyOverviewActivity.class);
			intent.putExtra("personId", person.getId().longValue());
			startActivity(intent);
		}
	}

	public void savePerson() {
		person.setName(etName.getText().toString());
		person.setSurname(etSurname.getText().toString());
		person.setGender(spGender.getSelectedItemPosition());
		Utility.getDaoSession().getPersonDao().insertOrReplace(person);
	}

	private boolean checkCreatedBirthDate() {
		if (getIntent().getLongExtra("personId", -1) == -1) {
			List<Event> birthEvents = PersonService.getEvents(person, "birth", "child");
			return (birthEvents.size() > 0 && EventService.getDate(birthEvents.get(0), "date") != null);
		}
		return true;
	}

	@Override
	public void onBackPressed() {
		Utility.getDB().endTransaction();
		Utility.refreshSession();
		super.onBackPressed();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			lvPersonEvents.setAdapter(new EventListAdapter(this,
					android.R.layout.simple_list_item_1, person, PersonService.getEvents(person)));
		}
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		switch (tabHost.getCurrentTab()) {
		case 1:
			// Ereignisse
			getMenuInflater().inflate(R.menu.events, menu);
			break;
		default:
			break;
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnuNewEvent:
			savePerson();

			Builder adb = new Builder(this);
			adb.setTitle(R.string.ttlSelectEventType);
			adb.setNegativeButton(R.string.btnCancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			adb.setAdapter(new EventTypeListAdapter(this, android.R.layout.simple_list_item_1,
					Utility.getDaoSession().getEventCodeDao().loadAll()),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			final AlertDialog dialog = adb.create();
			final ListView lv = dialog.getListView();
			lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
					dialog.dismiss();
					Intent intent = new Intent(PersonEditActivity.this,
							PersonEventEditActivity.class);
					intent.putExtra("personId", person.getId().longValue());
					intent.putExtra("eventTypeCode",
							((EventCode) lv.getItemAtPosition(position)).getCode());
					PersonEditActivity.this.startActivityForResult(intent, 0);
				}
			});
			dialog.show();
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		switch (tabHost.getCurrentTab()) {
		case 1:
			// Ereignisse
			getMenuInflater().inflate(R.menu.event_context, menu);
			break;
		default:
			break;
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.mnuDeleteEvent:
			// TODO
			break;
		default:
			break;
		}
		return true;
	}

	@Override
	public void onTabChanged(String tabId) {
		invalidateOptionsMenu();
	}

}
